package com.abc.easyclaim;

import java.util.ArrayList;
import java.util.List;

import com.abc.bean.Case;
import com.abc.bean.Record;
import com.abc.db.DBManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Environment;

//接收播放、暂停、停止等命令广播Intent的接收者
public class CommandReceiver extends BroadcastReceiver {
    MediaPlayer mp;//媒体播放器引用
    int status;//状态值
    int currentSound=-1;                  //当前播放录音序号
    int progress=0;          //进度条值
    String soundFilesPath;  //播放文件夹路径
    String currentPath;                //当前播放录音路径
    private Runnable runnable;                 //控制进度条线程
    private Thread thread;                    //线程
    private boolean stopThread = false;  
    private DBManager dbManager;           //数据库操作管理器
    private Case caze;
	private List<Record> records=new ArrayList<Record>();         //录音集合
	private int cazeId;           
	@Override
	public void onReceive(final Context context, Intent intent) {
		//从数据库中读取录音信息
		dbManager=new DBManager(context);
		cazeId=intent.getIntExtra("cazeId", -1);
		records=dbManager.queryRecords(cazeId);	
		caze=dbManager.queryCase(cazeId);
		//cazeName=intent.getStringExtra("cazeName");           //获取案例名
		soundFilesPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/"+caze.getName()+"/records";
		System.out.println("this.soundFilesPath="+soundFilesPath);
		//进度条线程
		runnable=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//当正在播放且未播放完时
					while(progress<records.get(currentSound).getLength() && status==Constant.STATUS_PLAY && !stopThread)
					{
						Thread.sleep(1000);
						progress++;                   //播放进度条前进
						if (status==Constant.STATUS_STOP) {
							progress=0;
						}
						//System.out.println("progress="+progress);
						//System.out.println("status="+status);
						//System.out.println("线程ID:"+Thread.currentThread().getId());  
			            //0System.out.println("线程name:"+Thread.currentThread().getName());
						//更新界面
						updateUI(context);
					}
					
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		};
		
		switch(intent.getIntExtra("cmd", -1))
		{
		  //根据收到命令的不同做不同的工作
			  
		  //收到播放命令
		  case Constant.COMMAND_PLAY:			  
			 //获取要播放歌曲的序号
			 int savecurrentSound=currentSound;          //保存currentSouond
			 currentSound=intent.getIntExtra("currentSound", -1);  
			 if(currentSound!=-1)
			 {
				 //若收到了currentSound说明是新的一轮播放
				 progress=0;        //进度条值初始化为0
				 currentPath=soundFilesPath+"/"+records.get(currentSound).getTitle();
				 //如果以前有播放器则释放
				 if(mp!=null){mp.release();}
				 //创建新的播放器
				 mp=new MediaPlayer();	
				 mp.setOnCompletionListener(//歌曲播放结束事件的监听器
						 new OnCompletionListener()
							{
								@Override
								public void onCompletion(MediaPlayer arg0) 
								{//歌曲播放结束停止播放并更新界面状态
									arg0.stop();
									status=Constant.STATUS_STOP;
									progress=0;        //进度条值初始化为0
									updateUI(context);
								}			
							}				 
				 );
				 try 
				 {
					//设置播放歌曲的路径
					mp.setDataSource(currentPath);
					//进行播放前的准备工作，new方式创建的MediaPlayer一定需要prepare
					//否则报错
					mp.prepare();
					//开始播放
					mp.start();
				 } catch (Exception e1) 
				 {					
					e1.printStackTrace();
				 }
			 }
			 else
			 {//若没有收到currentSound说明是暂停后的继续播放
				 currentSound=savecurrentSound;
				 mp.start();
			 }
			 //更新状态值到播放中状态
			 status=Constant.STATUS_PLAY;
			 stopThread=false;
			 thread=new Thread(runnable); 
			 thread.start();              //启动线程
		     break;
		   //收到暂停命令
		  case Constant.COMMAND_PAUSE:
			 mp.pause();//暂停播放 
			 stopThread=true;
			 status=Constant.COMMAND_PAUSE;//更新状态值到暂停状态
			 thread=new Thread(runnable); 
			 thread.start();              //启动线程
		     break;
		   //收到播放上一个命令
		  case Constant.COMMAND_PREVIOUS:
			//收到播放下一个命令
		  case Constant.COMMAND_NEXT:
		   //收到停止命令
			  currentSound=intent.getIntExtra("currentSound", -1);
		  case Constant.COMMAND_STOP:
			 mp.stop();//停止播放
			 progress=0;        //进度条值初始化为0
			 stopThread=true;
			 status=Constant.STATUS_STOP;//更新状态值到停止状态	
			 thread=new Thread(runnable); 
			 thread.start();              //启动线程
			 System.out.println("stop.progress="+progress);
		     break;
		  //收到改变进度条命令
		  case Constant.COMMAND_SETBAR:
			//获取传入的进度值
			 progress=intent.getIntExtra("progress", 0);
			 System.out.println("setbar_progress="+progress);
			 System.out.println("setbar_status="+status);
			 mp.seekTo(progress);   //当进度条值改变时，从新的位置开始播放音频
			 break;
		}
		//更新界面
		updateUI(context);
	}
	
	public void updateUI(Context context)
	{
		//创建Action为Constant.UPDATE_STATUS（更新界面）的Intent
		Intent intent =new Intent(Constant.UPDATE_STATUS);
		//将更新后的新状态值放到intent中
		intent.putExtra("status", status);
		intent.putExtra("currentSound", currentSound);
		intent.putExtra("progress", progress);
		//广播Intent
		context.sendBroadcast(intent);
	}

}
